<?php
/*  vim: set expandtab shiftwidth=4 softtabstop=4 tabstop=4:    */

class DBv2 {
    public  $db;
    private $masterPool = array();
    private $slavePool = array();    
    private static $required    =   array("engine", "host", "user", "password", "name");
    
    
    public function __construct($core,$dsn) {
        try {
           	$this->db = self::startEngine($core,$dsn);
        } catch (Exception $e) {
            print "Unable to initialize DB : ". $e->getMessage();
        }
    }
    
    public function __call($m,$a) {
    	switch($m) {
	    	case 'query':
	    	case 'tableDesc':
	    	case 'getPrimaryKey':
	    	case 'getForeignKey':
	    	case 'fetchFields':
	    	case 'clean':
	    		if(!empty($this->slavePool)) {
	    			return call_user_func_array(array($this->slavePool[$this->pickSlave()],$m),$a);
	    		} else {
	    			return call_user_func_array(array($this->db,$m),$a);
	    		}
	    	break;
    		default:
    			if(!empty($this->masterPool)) {
    				return call_user_func_array(array($this->masterPool[$this->pickMaster()],$m),$a);
    			} else {
    				return call_user_func_array(array($this->db,$m),$a);
    			}
    		break;
    	}
        return FALSE;
    }
    
    public function addMaster($core,$dsn) {
        try {
           	$this->masterPool[] = self::startEngine($core,$dsn);
        } catch (Exception $e) {
            print "Unable to initialize DB : ". $e->getMessage();
            return FALSE;
        }
        return TRUE;
    }
    
    public function addSlave($core,$dsn) {
        try {
           	$this->slavePool[] = self::startEngine($core,$dsn);
        } catch (Exception $e) {
            print "Unable to initialize DB : ". $e->getMessage();
            return FALSE;
        }
        return TRUE;
    }

    private function pickMaster() {
       	if(count($this->masterPool) > 1) {
    		return array_rand($this->masterPool);
    	} else {
    		return 0;
    	}
    }
    
    private function pickSlave() {
    	if(count($this->slavePool) > 1) {
    		return array_rand($this->slavePool);
    	} else {
    		return 0;
    	}
    }

    /*
     *  Kick-start the DB engine
     */
    public function startEngine($core,array $dsn) {
    	switch($core) {
    		case "PDO":
            default:
            	switch($dsn['engine']) {
            		case "dblib":
            			return new PDO_Mssql($dsn);
                    break;
                    default:
                        return new PDO_Mysql($dsn);
                    break;
                }
            break;
        }
        return FALSE;
    }

}

?>
